/******************************************************************************
** 
** Hex to digit coverter.
** 
** File name:	htoi.c
** Compilation:	cc htoi.c -o htoi
** Execution:	./htoi
** 
** Description:
** Reads a string - an optionally "0x" or "0X"-prefixed positive hexademical 
** max 8-digit number, converts it into a integer digit, and prints it 
** as a decimal.
** Inputted hex number must be exactly 4 hex digits (unsigned short int).
** 
******************************************************************************/
#include <stdio.h>
#include <limits.h>
#include <ctype.h>
#include "myfunctions.h"


#define HEX_NUMBER_MAX_DIGITS 8

// Constant nSML (numberAsStringMaxLength): possible "0x" + max 4 hex digits + '\0'
short int const nSML = 2+HEX_NUMBER_MAX_DIGITS+1;


int main()
{

    // Possible "0x" + max HEX_NUMBER_MAX_DIGITS hex digits + '\0'
    short int const nSMaxLength = 2+HEX_NUMBER_MAX_DIGITS+1;
    char nString[nSMaxLength];
    short int nStringLength;
    short int i;
    unsigned long digit;

    if ((nStringLength = GetString(nString, nSMaxLength)) != 0) {
        // Removing prepending "0x" if any:
        if (nString[0] == '0' && tolower(nString[1]) == 'x') {
            for (i=2; i<nStringLength; ++i) {
                nString[i-2] = nString[i];
            }
            nStringLength = nStringLength -2;
            nString[nStringLength] = ENDLINE_SYMBOL;
        }

        // Checking the amount of analyzed digits, if it is greater than HEX_NUMBER_MAX_DIGITS - it's an error:
        if (nStringLength > HEX_NUMBER_MAX_DIGITS) {
            printf("Error input: the amount of meaning hex digits must not be greater than %d, exiting.\n", HEX_NUMBER_MAX_DIGITS);
            return -1;
        }
        

        // Validating:
        for (i=0; i<nStringLength; ++i) {
            nString[i] = tolower(nString[i]);
            if (!((isdigit(nString[i])) || (nString[i] >= 'a' && nString[i] <= 'f'))) {
                printf("Error input: \'%c\' is not a hex digit, exiting.\n", nString[i]);
                return -1;
            }
        }

        // Transforming the string into a decimal digit:
        digit = 0;
        for (i=0; i<nStringLength; ++i) {
            if (isdigit(nString[i])) {
                digit = 16*digit + (nString[i]-'0');
            } else {
                digit = 16*digit + (nString[i]-'a'+10);
            }
        }
        printf("Decimal number:\t%u\n\n", digit);
    }

    return 0;
}

